package com.hengpeng.itfints.tools;

import java.io.StringWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import com.hengpeng.common.template.loader.StringTemplateLoader;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class CommonUtil
{
	public static Date formatCurrentDate(String format)
	{
		DateFormat dateFormat = new SimpleDateFormat(format);
		String date = dateFormat.format(new Date());
		try
		{
			return dateFormat.parse(date);
		}
		catch (ParseException e)
		{
			throw new RuntimeException("格式化时间异常");
		}
	}

	/**
	 * <pre>
	 * 读取a=1;b=2;c=3这种格式字符
	 * </pre>
	 * @param text
	 * @return
	 */
	public static Map<String, String> getConfigByStr(String text)
	{
		return getConfigByStr(text,";");
	}

	public static Map<String, String> getConfigByStr(String text, String split)
	{
		Map<String, String> result = new HashMap<String, String>();
		if (text != null)
		{
			text = text.trim();
			String[] entrys = text.split("\\" + split);
			for (String entry : entrys)
			{
				String[] values = entry.split("\\=");
				if (values.length == 2)
				{
					result.put(values[0], values[1]);
					//System.out.println(values[0] + "=" + values[1]);
				}
			}
		}
		return result;
	}

	public static String parseString(String text, Map<String, String> date)
	{
		Configuration cfg = new Configuration();
		cfg.setTemplateLoader(new StringTemplateLoader(text));
		cfg.setDefaultEncoding("UTF-8");
		StringWriter writer = new StringWriter();
		String message = null;
		try
		{
			Template template = cfg.getTemplate("");
			template.process(date, writer);
			message = writer.toString();
			writer.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return message;
	}
	/**
	 * 生成指定位数的随机数
	 * @param paramInt
	 * @return
	 */
	public static String getRandom(int paramInt)
	{
		Random localRandom = new Random();
		String str = "";
		for (int i = 0; i < paramInt; i++)
		{
			str = str + localRandom.nextInt(9);
		}
		return str;
	}

}
